package sessions;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entities.Abilita;
import entities.Amministratore;
import entities.Dichiara;
import entities.Utente;

@Stateless
public class UserManager implements UserManagerRemote, UserManagerLocal {
	@PersistenceContext(unitName = "SwimDB")
	EntityManager database;

	public UserManager() {	
	}
	public Utente getUserWithUsername(String userName) {
		try {
			Query q = database.createQuery("FROM Utente u WHERE u.userName=:userName");
			q.setParameter("userName",userName);
			return (Utente) q.getSingleResult();
		} catch (EntityNotFoundException exc) { 
		} catch (javax.persistence.NoResultException exc) { 
		} catch (NonUniqueResultException exc) {
		}
		return null;
	}

	public List<Utente> getUtenteDaNomeCognome(String nome, String cognome){
		List<Utente> nomi = new ArrayList<Utente>();

		try {
			Query q = database.createQuery("FROM Utente u WHERE u.nome=?1 AND u.cognome=?2");
			q.setParameter(1, nome);
			q.setParameter(2, cognome);
			List<?> risultato =  q.getResultList();
			if(risultato.isEmpty())
			{
				q=database.createQuery("FROM Utente u WHERE u.nome=?1");
				q.setParameter(1, nome);
				risultato =  q.getResultList();
				if(risultato.isEmpty())
				{
					q=database.createQuery("FROM Utente u WHERE u.cognome=?1");
					q.setParameter(1, cognome);
					risultato =  q.getResultList();
				}
			}
			
			for(Object obj: risultato) {
				nomi.add((Utente) obj);
			}
			
			
			return nomi;
		} catch (EntityNotFoundException exc) { 
		} catch (javax.persistence.NoResultException exc) { 
		} catch (NonUniqueResultException exc) {
		}
		return null;   	

	}

	public List<String> getUsernames() {
		List<String> names = new ArrayList<String>();
		try {
			Query q = database.createQuery("SELECT u.userName FROM Utente u");
			List<?> risultato =  q.getResultList();
			System.out.println("*** list size *** " + risultato.size());
			for(Object obj: risultato) {
				names.add((String) obj);
			}

		} catch (EntityNotFoundException exc) { 
		} catch (NonUniqueResultException exc) {
		}
		return names;
	}

	public void insertUser(Utente u){
		try {
			//	if(database.find(User.class, u.getID()) == null) {
			database.persist(u);
			//	}
		}catch(NoResultException e) {
			database.persist(u);
		}


	}
	@Override
	public boolean dichiaraAbilita(String userName, String nomeAbilita) {

		try {
			Query q = database.createQuery("SELECT u.IDUser FROM Utente u where u.userName=?1");
			q.setParameter(1, userName);
			long IDUser=((Long)q.getSingleResult()).longValue();
			System.out.println("*** userid *** " + IDUser);
			Utente utente=database.find(Utente.class, IDUser);

			q = database.createQuery("SELECT a.IDAbilita FROM Abilita a WHERE a.nomeAbilita=?1");
			q.setParameter(1, nomeAbilita);
			int IDAbilita= ((Integer) q.getSingleResult()).intValue();

			Abilita abilita=database.find(Abilita.class, IDAbilita);

			q = database.createQuery("FROM Dichiara d WHERE d.userRef=?1 AND d.abilitaRef=?2");
			q.setParameter(1, utente);
			q.setParameter(2, abilita);


			List<?> risultato =  q.getResultList();



			if(risultato.isEmpty())
			{
				Dichiara d=new Dichiara();
				d.setIdAbilita(abilita);
				d.setIDUser(utente);

				database.persist(d);
				return true;
			}


		} catch (EntityNotFoundException exc) { 
		} catch (NonUniqueResultException exc) {
			return false;
		}

		return false;
	}
	@Override
	public boolean validaCredenzialiUtente(String userName, String password) {
		try {
			Query q = database.createQuery("FROM Utente u where u.userName=?1 and u.password=?2");
			q.setParameter(1, userName);
			q.setParameter(2, password);
			List<?> risultato=q.getResultList();
			if(risultato.isEmpty())
				return false;

			return true;
		}catch (NonUniqueResultException exc){
			return false;
		}
	}
	@Override
	public boolean validaCredenzialiAmministratore(String userName,
			String password) {
		// TODO Auto-generated method stub
		try {
			Query q = database.createQuery("FROM Amministratore a where a.userName=?1 and a.password=?2");
			q.setParameter(1, userName);
			q.setParameter(2, password);
			List<?> risultato=q.getResultList();
			if(risultato.isEmpty())
				return false;

			return true;
		}catch (NonUniqueResultException exc){
			return false;
		}
	}
	public Amministratore getAmministratore(String userName)
	{
		Query q = database.createQuery("FROM Amministratore a where a.userName=?1");
		q.setParameter(1, userName);
		Amministratore a=(Amministratore) q.getSingleResult();
		return a;

	}
	@Override
	public void assegnaFeedbackMedio(Utente u) {

		Query q = database.createQuery("SELECT AVG(r.feedback) FROM RichiestaAiuto r where r.destinatario=?1 and responso=?2");
		q.setParameter(1, u);
		q.setParameter(2, "Accettata");
		double feedback= ((Double) q.getSingleResult()).doubleValue();
		Utente nuovoUtente=database.find(Utente.class, u.getIDUser());
		nuovoUtente.setFeedback((int)feedback);
		database.persist(nuovoUtente);

	}
	@Override
	public Utente getEntityUtente(long id) {
		return database.find(Utente.class, id);
	}
	@Override
	public void updateUser(Utente u1) {
		database.merge(u1);
		
	}

}
